package plgnet

import (
	"dgo/MyProj/PrjHttpUtils"
	"dgo/goutils/gohttp"
	"dgo/goutils/httpfs"
	"dgo/goutils/utils"
	"dgo/plg/plgbase"
	"fmt"
	"gitee.com/ymofen/gobase/golog"
	"gitee.com/ymofen/supervalue"
	"net/http"
	"strings"
)

type NetHttpFileSvrPlugin struct {
	plgbase.PlgBase
	pattern    string
	path       string
	listtype   string
	listfiles  bool
	allowcross bool
}

/*
**

	{
	  "id":"m-cloud",
	  "type":"net.http.filesvr",
	  "conf":{
		"pattern":"/cloud/m/",
	    "path":"/home/kpl/cloud/m",
	    "listtype":"json",
	    "listfiles":false
	   }
	}
*/
func (this *NetHttpFileSvrPlugin) ReloadConf(conf *wrapper.SuperValue) error {
	if conf == nil {
		return nil
	}

	pattern_pre := this.pattern
	isChanged := false
	conf.CheckStrFunc("pattern", func(strv string) {
		if this.pattern != strv {
			isChanged = true
			this.pattern = strv
		}
	})

	conf.CheckStrFunc("path", func(strv string) {
		if this.path != strv {
			isChanged = true

			this.path = strv
		}
	})

	conf.CheckStrFunc("listtype", func(strv string) {
		if this.listtype != strv {
			this.listtype = strv
			isChanged = true
		}
	})

	conf.CheckStrFunc("listfiles", func(strv string) {
		b := utils.TryStrToBool(strv, true)
		if b != this.listfiles {
			isChanged = true
			this.listfiles = b
		}
	})

	if isChanged {
		gohttp.UnHandle(pattern_pre)
		if len(this.pattern) > 0 {
			if len(this.listtype) == 0 {
				this.listtype = "html"
			}
			lsttype := 0
			if strings.ToLower(this.listtype) == "json" {
				lsttype = 1
			}
			fserv := httpfs.FileServer(http.Dir(this.path), lsttype, func(w http.ResponseWriter, r *http.Request) bool {
				if this.allowcross {
					PrjHttpUtils.AllowCrossAccessSet(w)
				}
				return true
			})
			fserv.ListFiles = this.listfiles
			if gohttp.Handle(this.pattern, http.StripPrefix(this.pattern, fserv)) {
				golog.Infof("pattern:[%s], path:[%s], listtype:%s, listfiles:%s", this.pattern, this.path, this.listtype, utils.Bool2Str(this.listfiles))
			} else {
				panic(fmt.Sprintf("pattern:[%s], path:[%s], listtype:%s, listfiles:%s, 注册失败, 请检查是否启用http插件", this.pattern, this.path, this.listtype, utils.Bool2Str(this.listfiles)))
			}
		}
	}

	return nil
}

func (this *NetHttpFileSvrPlugin) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		} else {
			err = fmt.Errorf("非法的JSON配置")
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {
		if len(this.pattern) > 0 {
			gohttp.UnHandle(this.pattern)
		}
	}
	return
}

func CreateNetHttpFileSvrPlugFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &NetHttpFileSvrPlugin{}
	obj.allowcross = true
	obj.listfiles = true
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.PlugId = str
		}
	}
	rval = obj
	return
}
